{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 通义调用"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "https://help.aliyun.com/zh/model-studio/developer-reference/use-qwen-by-calling-api?spm=a2c6h.13066369.question.6.66921a939nAhba#1d4417c9ae7tn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-03-26T02:55:05.393563Z",
     "start_time": "2025-03-26T02:55:02.631509Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"id\":\"chatcmpl-3d088b3e-f085-9480-97a4-4f5f280b1975\",\"choices\":[{\"finish_reason\":\"stop\",\"index\":0,\"logprobs\":null,\"message\":{\"content\":\"我是通义千问，阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我能够回答问题、创作文字，如写故事、公文、邮件、剧本等，还能进行逻辑推理、编程，甚至表达观点和玩游戏。我在多国语言上都有很好的掌握，能为你提供多样化的帮助。如果你有任何问题或需要创作的内容，随时可以告诉我！\",\"refusal\":null,\"role\":\"assistant\",\"audio\":null,\"function_call\":null,\"tool_calls\":null}}],\"created\":1744684482,\"model\":\"qwen-plus\",\"object\":\"chat.completion\",\"service_tier\":null,\"system_fingerprint\":null,\"usage\":{\"completion_tokens\":80,\"prompt_tokens\":21,\"total_tokens\":101,\"completion_tokens_details\":null,\"prompt_tokens_details\":{\"audio_tokens\":null,\"cached_tokens\":0}}}\n",
      "我是通义千问，阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我能够回答问题、创作文字，如写故事、公文、邮件、剧本等，还能进行逻辑推理、编程，甚至表达观点和玩游戏。我在多国语言上都有很好的掌握，能为你提供多样化的帮助。如果你有任何问题或需要创作的内容，随时可以告诉我！\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from openai import OpenAI\n",
    "\n",
    "client = OpenAI(\n",
    "    # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key=\"sk-xxx\",\n",
    "    api_key=os.getenv(\"DASHSCOPE_API_KEY\",\"sk-56ccc866f8444c89944b4d6c833897b5\"), \n",
    "    base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
    ")\n",
    "completion = client.chat.completions.create(\n",
    "    model=\"qwen-plus\", # 此处以qwen-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models\n",
    "    messages=[\n",
    "        {'role': 'system', 'content': 'You are a helpful assistant.'},\n",
    "        {'role': 'user', 'content': '你是谁'}],\n",
    "    )\n",
    "    \n",
    "print(completion.model_dump_json())\n",
    "print(completion.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 流式输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from openai import OpenAI\n",
    "\n",
    "client = OpenAI(\n",
    "    # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key=\"sk-xxx\",\n",
    "    api_key=os.getenv(\"DASHSCOPE_API_KEY\",\n",
    "                      \"sk-56ccc866f8444c89944b4d6c833897b5\"),\n",
    "    base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
    ")\n",
    "completion = client.chat.completions.create(\n",
    "    # 此处以qwen-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models\n",
    "    model=\"qwen-plus\",\n",
    "    messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},\n",
    "              {'role': 'user', 'content': '宇宙是如何开始的？'}],\n",
    "    stream=True,\n",
    "    stream_options={\"include_usage\": True}\n",
    "    # max_tokens=8192\n",
    ")\n",
    "for chunk in completion:\n",
    "    if len(chunk.choices) > 0:\n",
    "        print(chunk.choices[0].delta.content, end=\"\")\n",
    "print()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "rag",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
